package com.ys.service.storage.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.dto.AddDto;
import com.ys.dto.EditDto;
import com.ys.entity.business.TbBaseInfo;
import com.ys.entity.finance.TcwDepositPlatform;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.purchase.TcgPurchaseByOrder;
import com.ys.entity.purchase.TcgPurchaseByOrderSon;
import com.ys.entity.storage.TccOnlinePurchaseReturn;
import com.ys.entity.storage.TccOnlinePurchaseReturnItem;
import com.ys.entity.storage.TccStockControl;
import com.ys.entity.storage.TccStockFrozenRunning;
import com.ys.entity.sys.*;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.enume.finance.TcwAccountCountForWanliEnum;
import com.ys.enume.finance.TcwFinancialTransactionFlowEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.storage.TccStockFrozenRunningEnum;
import com.ys.enume.storage.TccStockSourceEnum;
import com.ys.mapper.purchase.TcgPurchaseByOrderMapper;
import com.ys.mapper.storage.TccOnlinePurchaseReturnItemMapper;
import com.ys.mapper.storage.TccOnlinePurchaseReturnMapper;
import com.ys.mapper.storage.TccStockFrozenRunningMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForWanliService;
import com.ys.service.finance.TcwFinancialTransactionFlowService;
import com.ys.service.finance.TcwWanliPrepaymentPoolingService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.purchase.Api1688Service;
import com.ys.service.storage.TccOnlinePurchaseReturnService;
import com.ys.service.storage.TccStockControlService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.ApiResponse;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("tccOnlinePurchaseReturnService")
public class TccOnlinePurchaseReturnServiceImpl implements TccOnlinePurchaseReturnService {

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private TccOnlinePurchaseReturnMapper tccOnlinePurchaseReturnMapper;

    @Autowired
    private TccOnlinePurchaseReturnItemMapper tccOnlinePurchaseReturnItemMapper;

    @Autowired
    private YspTaskService yspTaskService;

    @Autowired
    private TccStockControlService tccStockControlService;

    @Autowired
    private TccStockFrozenRunningMapper tccStockFrozenRunningMapper;

    @Autowired
    private TcwWanliPrepaymentPoolingService tcwWanliPrepaymentPoolingService;

    @Autowired
    private TcwAccountCountForWanliService tcwAccountCountForWanliService;

    @Autowired
    private TcwFinancialTransactionFlowService tcwFinancialTransactionFlowService;

    @Autowired
    private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

    @Autowired
    private Api1688Service api1688Service;

    @Autowired
    private TcgPurchaseByOrderMapper tcgPurchaseByOrderMapper;

    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R add(Map<String, Object> params, String subData) throws Exception {
        //验证
        String msg = yzMsg(params);
        if (msg != null){
            return R.error(msg);
        }
        TccOnlinePurchaseReturn tccOnlinePurchaseReturn = JSON.parseObject(JSON.toJSONString(params), TccOnlinePurchaseReturn.class);
        if (new TccOnlinePurchaseReturn().setBid(tccOnlinePurchaseReturn.getBid()).count() != 0){
            return R.error("该单号已存在，核实后再操作!");
        }
        if (tccOnlinePurchaseReturn.getRefundAmount() == BigDecimal.ZERO){
            return R.error("退款总额不允许为0");
        }
        if (tccOnlinePurchaseReturn.getRefundServiceCharge() == BigDecimal.ZERO){
            return R.error("采购服务费(退回)不允许为0");
        }

        // 验证是否有详情数据
        JSONArray detailJA = JSON.parseArray(subData);
        if (detailJA == null || detailJA.size() == 0) {
            return R.error("详情数据不能为空");
        }

        Integer subRefundNumNew = 0;
        //退货占比总额
        BigDecimal proportionTotal = BigDecimal.ZERO;
        for (int i = 0; i < detailJA.size(); i++) {
            JSONObject detailJO = detailJA.getJSONObject(i);
            TccOnlinePurchaseReturnItem tccOnlinePurchaseReturnItem = JSON.parseObject(JSON.toJSONString(detailJO), TccOnlinePurchaseReturnItem.class);
            if (tccOnlinePurchaseReturnItem.getSubRefundNum() == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error("子件退货数量不允许为空!");
            }
            subRefundNumNew = subRefundNumNew + tccOnlinePurchaseReturnItem.getSubRefundNum();

            proportionTotal = proportionTotal.add(detailJO.getBigDecimal("subAmount").multiply(detailJO.getBigDecimal("subRealityPrice"))
                    .multiply(new BigDecimal(tccOnlinePurchaseReturnItem.getSubRefundNum())));
        }

        if(subRefundNumNew == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error("该单据不允许退货数量全为0!");
        }

        String loginUserId = ShiroUtils.getUserId();
        TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();

        tccOnlinePurchaseReturn.setStatus(1);
        tccOnlinePurchaseReturn.setCreateChangeId(tsUserChange.getId());
        tccOnlinePurchaseReturn.setEffectStock(FlowEnum.EffectStock.NOT_EFFECT.value);

        if (tccOnlinePurchaseReturn.getStorageCommissionCharge() == null) {
            tccOnlinePurchaseReturn.setStorageCommissionCharge(BigDecimal.ZERO);
        }
        if (tccOnlinePurchaseReturn.getLogisticsCost() == null) {
            tccOnlinePurchaseReturn.setLogisticsCost(BigDecimal.ZERO);
        }
        tccOnlinePurchaseReturnMapper.insert(tccOnlinePurchaseReturn);

        for (int i = 0; i < detailJA.size(); i++) {
            JSONObject detailJO = detailJA.getJSONObject(i);
            TccOnlinePurchaseReturnItem tccOnlinePurchaseReturnItem = JSON.parseObject(JSON.toJSONString(detailJO), TccOnlinePurchaseReturnItem.class);

            tccOnlinePurchaseReturnItem.setPid(tccOnlinePurchaseReturn.getId());

            BigDecimal subRefundPrice = BigDecimal.ZERO;
            if (tccOnlinePurchaseReturnItem.getSubRefundNum() != 0){
                BigDecimal zbDecimal = (detailJO.getBigDecimal("subAmount").multiply(detailJO.getBigDecimal("subRealityPrice"))
                        .multiply(new BigDecimal(tccOnlinePurchaseReturnItem.getSubRefundNum()))).divide(proportionTotal,3,BigDecimal.ROUND_HALF_UP);
                BigDecimal refundAmount = zbDecimal.multiply(tccOnlinePurchaseReturn.getRefundAmount());
                subRefundPrice = refundAmount.divide(new BigDecimal(tccOnlinePurchaseReturnItem.getSubRefundNum()),3,BigDecimal.ROUND_HALF_UP);
            }

            tccOnlinePurchaseReturnItem.setSubRefundPrice(subRefundPrice);
            tccOnlinePurchaseReturnItemMapper.insert(tccOnlinePurchaseReturnItem);

            TcgPurchaseByOrderSon tcgPurchaseOrderSon = new TcgPurchaseByOrderSon().setId(tccOnlinePurchaseReturnItem.getPurchaseOrderSonId()).queryFirst();
            TcgPurchaseByOrder tcgPurchaseOrder = new TcgPurchaseByOrder().setId(tcgPurchaseOrderSon.getPid()).queryFirst();

           if (tccOnlinePurchaseReturn.getIsRefund() == 1) {
               //只能分配对应公司名下的可用库存
               List<TccStockControl> tccStockControlList = new TccStockControl()
                       .setVgsbm(tcgPurchaseOrder.getVgsbm())
                       .setProductCode(tcgPurchaseOrderSon.getSubCode())
                       .where("A.productNum > 0")
                       .setOrderby("A.Drksj ASC")
                       .queryList();
               if (tccStockControlList.size() == 0) {
                   TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                   return R.error(tcgPurchaseOrderSon.getSubCode() + "库存不足,请核实后在操作!");
               }
               //在库天数时间长的先分配
               Integer subRefundNum = tccOnlinePurchaseReturnItem.getSubRefundNum();
               Integer bcNum = 0;
               for (TccStockControl tccStockControl : tccStockControlList) {
                   if (subRefundNum != 0) {
                       //库存足够直接扣减
                       if (tccStockControl.getProductNum() >= subRefundNum) {
                           bcNum = subRefundNum;
                           subRefundNum = 0;
                       } else {
                           bcNum = tccStockControl.getProductNum();
                           subRefundNum = subRefundNum - bcNum;
                       }
                       //冻结库存
                       Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_ONLINEPURCHASERETURN_PASS.value;
                       String sourceBid = tccOnlinePurchaseReturn.getBid();
                       Long sourceId = tccOnlinePurchaseReturn.getId();
                       tccStockControlService.frozen(tccStockControl.getId(), bcNum, sourceType, sourceBid, sourceId);

                   }
               }
               if (subRefundNum != 0) {
                   TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                   return R.error(tcgPurchaseOrderSon.getSubCode() + "库存不足,请核实后在操作!");
               }
           }
        }


        YsMenu ysMenu = new YsMenu().setId(MenuId.TCC_OnlinePurchaseReturn).queryFirst();
        if (ysMenu.getFlowModelId().longValue() != 0L) {
            YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
            String codeModel = yspModel.getCode();
            String createUserId = ShiroUtils.getUserId();
            yspTaskService.init(codeModel, tccOnlinePurchaseReturn.getBid(), createUserId);
        }
        return R.ok(AddDto.gotoEdit("/web/storage/tccOnlinePurchaseReturn/toEdit?bid=" + tccOnlinePurchaseReturn.getBid()));
    }

    private String yzMsg(Map<String, Object> infoMap){
        //验证导入字段
        String backMsg = "";
        //获取pc字段数据
        List<YsCol> listField = new YsCol()
                .where("A.MenuId = "+ MenuId.TCC_OnlinePurchaseReturn)
                .setOrderby("A.SortNo ASC")
                .queryList();
        //验证必填字段的非空；其他字段的长度限制、类型
        try {
            backMsg = checkUtil.checkTableColLengthAndDataType(
                    "TCC_OnlinePurchaseReturn",
                    listField,
                    infoMap,
                    ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1
            );
            if(backMsg!=null && !"".equals(backMsg)){//若有误，则跳过这条信息
                return backMsg;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R deleteTrue(Long id) throws Exception {
        if (id == null) {
            return R.error("ID不能为空");
        }

        TccOnlinePurchaseReturn entity = new TccOnlinePurchaseReturn().setId(id).queryFirst();
        if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
            return R.error("已生效数据无法删除");
        }
        deleteItem(entity);

        tccOnlinePurchaseReturnMapper.deleteTrue(id);

        String loginUserId = ShiroUtils.getUserId();
        yspTaskService.flowDelete(entity.getBid(), loginUserId);
        return R.ok(EditDto.closeAndReload());
    }


    /**
     * 删除子件信息
     * @param entity
     * @return
     */
    private R deleteItem(TccOnlinePurchaseReturn entity){
        try {
            List<TccOnlinePurchaseReturnItem> tccOnlinePurchaseReturnItemList = new TccOnlinePurchaseReturnItem()
                    .setPid(entity.getId())
                    .queryList();
            for(TccOnlinePurchaseReturnItem tccOnlinePurchaseReturnItem : tccOnlinePurchaseReturnItemList){
                tccOnlinePurchaseReturnItemMapper.deleteTrue(tccOnlinePurchaseReturnItem.getId());
            }

            if (entity.getIsRefund() == 1) {
                //解冻
                List<TccStockFrozenRunning> tccStockFrozenRunningList = new TccStockFrozenRunning()
                        .setSourceBid(entity.getBid())
                        .setSourceType(TccStockFrozenRunningEnum.SourceType.TCC_ONLINEPURCHASERETURN_PASS.value)
                        .setStatus(1)
                        .where("A.numChange > 0")
                        .queryList();
                for (TccStockFrozenRunning tccStockFrozenRunning : tccStockFrozenRunningList) {
                    tccStockFrozenRunning.setStatus(0);
                    tccStockFrozenRunningMapper.update(tccStockFrozenRunning);
                    String sourceBid = entity.getBid();
                    Long sourceId = entity.getId();
                    Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_ONLINEPURCHASERETURN_FINISH.value;
                    tccStockControlService.thaw(tccStockFrozenRunning.getStockControlId(), tccStockFrozenRunning.getNumChange(), sourceType, sourceBid, sourceId);
                }
            }
        }catch (Exception e){
            return R.error(e.getMessage());
        }
        return R.ok();
    }


    /**
     * 修改
     * @param params
     * @param subData
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R edit(Map<String, Object> params, String subData) throws Exception {
        //验证
        String msg = yzMsg(params);
        if (msg != null){
            return R.error(msg);
        }
        TccOnlinePurchaseReturn tccOnlinePurchaseReturn = JSON.parseObject(JSON.toJSONString(params), TccOnlinePurchaseReturn.class);
        Integer flowState = yspTaskService.flowState(tccOnlinePurchaseReturn.getBid());
        if (flowState == 1) {
            //审批保存
            TccOnlinePurchaseReturn tccOnlinePurchaseReturnNew = new TccOnlinePurchaseReturn();
            tccOnlinePurchaseReturnNew.setId(tccOnlinePurchaseReturn.getId());
            tccOnlinePurchaseReturnNew.setAliLogisticsPlace(tccOnlinePurchaseReturn.getAliLogisticsPlace());
            tccOnlinePurchaseReturnNew.setAliLogisticsCode(tccOnlinePurchaseReturn.getAliLogisticsCode());
            if (tccOnlinePurchaseReturn.getLogisticsCost() == null) {
                tccOnlinePurchaseReturnNew.setLogisticsCost(BigDecimal.ZERO);
            }else {
                tccOnlinePurchaseReturnNew.setLogisticsCost(tccOnlinePurchaseReturn.getLogisticsCost());

            }
            if (tccOnlinePurchaseReturn.getStorageCommissionCharge() == null) {
                tccOnlinePurchaseReturnNew.setStorageCommissionCharge(BigDecimal.ZERO);
            }else {
                tccOnlinePurchaseReturnNew.setStorageCommissionCharge(tccOnlinePurchaseReturn.getStorageCommissionCharge());
            }
            tccOnlinePurchaseReturnMapper.update(tccOnlinePurchaseReturnNew);
        }else {
            if (new TccOnlinePurchaseReturn().setPurchaseOrderId(tccOnlinePurchaseReturn.getPurchaseOrderId()).where("A.id != " + tccOnlinePurchaseReturn.getId()).count() != 0) {
                return R.error("该采购完成单已退货，核实后再操作!");
            }
            if (tccOnlinePurchaseReturn.getRefundAmount() == BigDecimal.ZERO) {
                return R.error("退款总额不允许为0");
            }
            if (tccOnlinePurchaseReturn.getRefundServiceCharge() == BigDecimal.ZERO) {
                return R.error("采购服务费(退回)不允许为0");
            }

            // 验证是否有详情数据
            JSONArray detailJA = JSON.parseArray(subData);
            if (detailJA == null || detailJA.size() == 0) {
                return R.error("详情数据不能为空");
            }

            Integer subRefundNumNew = 0;
            //退货占比总额
            BigDecimal proportionTotal = BigDecimal.ZERO;
            for (int i = 0; i < detailJA.size(); i++) {
                JSONObject detailJO = detailJA.getJSONObject(i);
                TccOnlinePurchaseReturnItem tccOnlinePurchaseReturnItem = JSON.parseObject(JSON.toJSONString(detailJO), TccOnlinePurchaseReturnItem.class);
                if (tccOnlinePurchaseReturnItem.getSubRefundNum() == null) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("子件退货数量不允许为空!");
                }
                subRefundNumNew = subRefundNumNew + tccOnlinePurchaseReturnItem.getSubRefundNum();

                proportionTotal = proportionTotal.add(detailJO.getBigDecimal("subAmount").multiply(detailJO.getBigDecimal("subRealityPrice"))
                        .multiply(new BigDecimal(tccOnlinePurchaseReturnItem.getSubRefundNum())));
            }

            if(subRefundNumNew == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error("该单据不允许退货数量全为0!");
            }

            //查询以前的信息
            TccOnlinePurchaseReturn entity = new TccOnlinePurchaseReturn().setBid(tccOnlinePurchaseReturn.getBid()).queryFirst();
            if (tccOnlinePurchaseReturn.getLogisticsCost() == null) {
                tccOnlinePurchaseReturn.setLogisticsCost(BigDecimal.ZERO);
            }
            if (tccOnlinePurchaseReturn.getStorageCommissionCharge() == null) {
                tccOnlinePurchaseReturn.setStorageCommissionCharge(BigDecimal.ZERO);
            }
            tccOnlinePurchaseReturnMapper.update(tccOnlinePurchaseReturn);

            //将之前的库存删除
            deleteItem(entity);

            for (int i = 0; i < detailJA.size(); i++) {
                JSONObject detailJO = detailJA.getJSONObject(i);
                TccOnlinePurchaseReturnItem tccOnlinePurchaseReturnItem = JSON.parseObject(JSON.toJSONString(detailJO), TccOnlinePurchaseReturnItem.class);

                tccOnlinePurchaseReturnItem.setPid(tccOnlinePurchaseReturn.getId());

                BigDecimal subRefundPrice = BigDecimal.ZERO;
                if (tccOnlinePurchaseReturnItem.getSubRefundNum() != 0){
                    BigDecimal zbDecimal = (detailJO.getBigDecimal("subAmount").multiply(detailJO.getBigDecimal("subRealityPrice"))
                            .multiply(new BigDecimal(tccOnlinePurchaseReturnItem.getSubRefundNum()))).divide(proportionTotal,3,BigDecimal.ROUND_HALF_UP);
                    BigDecimal refundAmount = zbDecimal.multiply(tccOnlinePurchaseReturn.getRefundAmount());
                    subRefundPrice = refundAmount.divide(new BigDecimal(tccOnlinePurchaseReturnItem.getSubRefundNum()),3,BigDecimal.ROUND_HALF_UP);
                }

                tccOnlinePurchaseReturnItem.setSubRefundPrice(subRefundPrice);
                tccOnlinePurchaseReturnItemMapper.insert(tccOnlinePurchaseReturnItem);

                TcgPurchaseByOrderSon tcgPurchaseOrderSon = new TcgPurchaseByOrderSon().setId(tccOnlinePurchaseReturnItem.getPurchaseOrderSonId()).queryFirst();
                TcgPurchaseByOrder tcgPurchaseOrder = new TcgPurchaseByOrder().setId(tcgPurchaseOrderSon.getPid()).queryFirst();

                if (tccOnlinePurchaseReturn.getIsRefund() == 1) {
                    //只能分配对应公司名下的可用库存
                    List<TccStockControl> tccStockControlList = new TccStockControl()
                            .setVgsbm(tcgPurchaseOrder.getVgsbm())
                            .setProductCode(tcgPurchaseOrderSon.getSubCode())
                            .where("A.productNum > 0")
                            .setOrderby("A.Drksj ASC")
                            .queryList();
                    if (tccStockControlList.size() == 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error(tcgPurchaseOrderSon.getSubCode() + "库存不足,请核实后在操作!");
                    }
                    //在库天数时间长的先分配
                    Integer subRefundNum = tccOnlinePurchaseReturnItem.getSubRefundNum();
                    Integer bcNum = 0;
                    for (TccStockControl tccStockControl : tccStockControlList) {
                        if (subRefundNum != 0) {
                            //库存足够直接扣减
                            if (tccStockControl.getProductNum() >= subRefundNum) {
                                bcNum = subRefundNum;
                                subRefundNum = 0;
                            } else {
                                bcNum = tccStockControl.getProductNum();
                                subRefundNum = subRefundNum - bcNum;
                            }
                            //冻结库存
                            Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_ONLINEPURCHASERETURN_PASS.value;
                            String sourceBid = tccOnlinePurchaseReturn.getBid();
                            Long sourceId = tccOnlinePurchaseReturn.getId();
                            tccStockControlService.frozen(tccStockControl.getId(), bcNum, sourceType, sourceBid, sourceId);

                        }
                    }
                    if (subRefundNum != 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return R.error(tcgPurchaseOrderSon.getSubCode() + "库存不足,请核实后在操作!");
                    }
                }
            }
        }

        return R.ok(AddDto.gotoEdit("/web/storage/tccOnlinePurchaseReturn/toEdit?bid=" + tccOnlinePurchaseReturn.getBid()));
    }


    /**
     * 线上采购退货单流转
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowPass(Long id, String loginUserId) throws Exception {
        TccOnlinePurchaseReturn entity = new TccOnlinePurchaseReturn().setId(id).queryFirst();
        String bid = entity.getBid();
        try {
            YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
            // 若流程是初始化状态，需要验证账户金额
            if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
                TcgPurchaseByOrder tcgPurchaseByOrder = new TcgPurchaseByOrder().setId(entity.getPurchaseOrderId()).queryFirst();
                R r = api1688Service.get1688AliState(tcgPurchaseByOrder.getAliOrderNumber());
                if (r.getCode() == 0){
                    tcgPurchaseByOrder.setAliState(r.getMsg());
                    tcgPurchaseByOrderMapper.update(tcgPurchaseByOrder);
                } else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("获取1688订单状态失败!");
                }
            }
            Flow f = yspTaskService.flowPass(bid, loginUserId);
            if (f.getCode() == Flow.Code.FAILED.value) {
                return R.error(f.getMsg());
            } else {
                if (f.getState() == Flow.State.FINISH.value) {
                    R r = flowFinish(entity);
                    if (r.getCode() == 1) {
                        return R.error(r.getMsg());
                    }
                }
                return R.ok();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 流转最后一步
     * @param entity
     * @return
     * @throws Exception
     */
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public R flowFinish(TccOnlinePurchaseReturn entity) throws Exception {
        try {
            if (entity.getIsRefund() == 1){
                if (entity.getAliLogisticsPlace() == null){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("发货物流方式不允许为空!");
                }
                if (entity.getAliLogisticsCode() == null){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("发货物流单号不允许为空!");
                }
                if (entity.getLogisticsCost() == null){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("物流成本不允许为空!");
                }
                if (entity.getStorageCommissionCharge() == null){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("仓储手续费不允许为空!");
                }
            }

            //查询1688订单编号
            TcgPurchaseByOrder tcgPurchaseOrder = new TcgPurchaseByOrder().setId(entity.getPurchaseOrderId()).queryFirst();

            R r = api1688Service.get1688AliState(tcgPurchaseOrder.getAliOrderNumber());
            if (r.getCode() == 0){
                tcgPurchaseOrder.setAliState(r.getMsg());
                tcgPurchaseByOrderMapper.update(tcgPurchaseOrder);
            }else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error("获取1688订单状态失败!");
            }

            //备注
            String remark = "采购退货单号:" + entity.getBid() + ",1688订单编号:"+tcgPurchaseOrder.getAliOrderNumber() + ",采购订单:" + tcgPurchaseOrder.getBid() ;
            //支付
            if (entity.getRefundPayType() == 1){
                //查询系统数据
                TbStaticConfig tbStaticConfig = new TbStaticConfig().setKeyOne("wanli-mid").setKeyTwo("wanli-mid-cs").queryFirst();
                //查询莫程收款平台账号管理
                TcwDepositPlatform tcwDepositPlatform = new TcwDepositPlatform().setMid(tbStaticConfig.getName()).queryFirst();
                //跨境宝获取退款手续费
                ApiResponse apiResponse = tcwWanliPrepaymentPoolingService.inquiryStatementListPaymentTh(tcwDepositPlatform, entity, tcgPurchaseOrder.getAliOrderNumber());
                if (apiResponse.getCode() == 500 || entity.getRefundCommissionCharge() == null || entity.getRefundWanliCharge() == null || entity.getRefund1688Charge() == null){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("获取退款手续费失败,流转失败!");
                }

                //新增万里汇流水
                //3、退货总额 + 付款手续费（退回）
                R res3 = tcwAccountCountForWanliService.add(true,"ZHBM00001", "CNH", TcwAccountCountForWanliEnum.DocumentType.TCC_OnlinePurchaseReturn.value,
                        entity.getBid(),entity.getRefundAmount().add(entity.getRefundCommissionCharge()), remark);
                if(res3.getCode().equals(R.Code.FAILED.value)){//失败
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error(res3.getMsg());
                }
            }else {
                //支付宝 -财务流水
                //获取交易类型
                String transactionTypeStr = TransactionTypeEnum.BusinessType.CGFW_CGCBZC.name;
                TbBaseInfo transactionTypeItem = tcwFinancialTransactionFlowService.getTransactionType(transactionTypeStr);
                //获取银行账户信息
                TbCompanyBankInfo tbCompanyBankInfo = new TbCompanyBankInfo().setVid(entity.getRefundVid()).queryFirst();
                if(tbCompanyBankInfo==null || tbCompanyBankInfo.getId()==null){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error("未查询到对应的银行账户信息");
                }

                if(transactionTypeItem!=null && transactionTypeItem.getId()!=null){
                    R res = tcwFinancialTransactionFlowService.add(true, tbCompanyBankInfo.getId(),
                            transactionTypeItem.getBid(),"1688采购平台", "1688采购平台", "1688采购平台",
                            entity.getRefundAmount(),
                            entity.getCreateTime(),new Date(),new Date(),remark,
                            TcwFinancialTransactionFlowEnum.FromType.TCC_OnlinePurchaseReturn.value,entity.getId());
                    if(res.getCode().equals(R.Code.FAILED.value)){//失败
                        String reeorMsg = res.getMsg();
                        throw new IllegalArgumentException(reeorMsg);
                    }
                }
            }

            //收入
            //1、+退货总额
            R res1 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                    "GS0607","采购部", "1688", "1688采购平台",
                    TransactionTypeEnum.BusinessType.CGFW_CGCBZC.name, entity.getRefundAmount(),
                    entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
            if(res1.getCode().equals(R.Code.FAILED.value)){//失败
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return R.error(res1.getMsg());
            }
            if (entity.getRefundPayType() == 1){
                //3、-WF付款手续费
                R res3 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        "GS0607","采购部", "WorldFirst", "WorldFirst支付平台",
                        TransactionTypeEnum.BusinessType.CGFW_SXF.name, entity.getRefundWanliCharge(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
                if(res3.getCode().equals(R.Code.FAILED.value)){//失败
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error(res3.getMsg());
                }
                //3、-1688手续费
                R res33 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        "GS0607","采购部", "1688", "1688采购平台",
                        TransactionTypeEnum.BusinessType.CGFW_SXF.name, entity.getRefund1688Charge(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
                if(res33.getCode().equals(R.Code.FAILED.value)){//失败
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return R.error(res3.getMsg());
                }
            }


            ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(tcgPurchaseOrder.getVgsbm()).queryFirst();
            R res11 = R.ok();
            R res12 = R.ok();
            if (entity.getRefundAmount().compareTo(BigDecimal.ZERO) != 0){
                //1、“+”退货总额
                res11 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        tcgPurchaseOrder.getVgsbm(),thrOperateCompanyApply.getVgsjc(), "GS0607", "采购部",
                        TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name, entity.getRefundAmount(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
                //1、-退货总额
                res12 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        "GS0607","采购部",  tcgPurchaseOrder.getVgsbm(),thrOperateCompanyApply.getVgsjc(),
                        TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name, entity.getRefundAmount().negate(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
            }

            R res13 = R.ok();
            R res14 = R.ok();
            if (entity.getRefundServiceCharge().compareTo(BigDecimal.ZERO) != 0){
                //1、+采购服务→代理采购服务费
                res13 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        tcgPurchaseOrder.getVgsbm(),thrOperateCompanyApply.getVgsjc(), "GS0607", "采购部",
                        TransactionTypeEnum.BusinessType.CGFW_DLCGFWF.name, entity.getRefundServiceCharge(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
                //1、-采购服务→代理采购服务费
                res14 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        "GS0607","采购部",  tcgPurchaseOrder.getVgsbm(),thrOperateCompanyApply.getVgsjc(),
                        TransactionTypeEnum.BusinessType.CGFW_DLCGFWF.name, entity.getRefundServiceCharge().negate(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
            }

            R res15 = R.ok();
            R res16 = R.ok();
            if (entity.getLogisticsCost().compareTo(BigDecimal.ZERO) != 0){
                //1、-物流成本
                res15 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        tcgPurchaseOrder.getVgsbm(),thrOperateCompanyApply.getVgsjc(), "GS0608", "仓储部",
                        TransactionTypeEnum.BusinessType.CCFW_KDF.name, entity.getLogisticsCost().negate(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
                //1、+物流成本
                res16 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        "GS0608","仓储部",  tcgPurchaseOrder.getVgsbm(),thrOperateCompanyApply.getVgsjc(),
                        TransactionTypeEnum.BusinessType.CCFW_KDF.name, entity.getLogisticsCost(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
            }

            R res17 = R.ok();
            R res18 = R.ok();
            if (entity.getStorageCommissionCharge().compareTo(BigDecimal.ZERO) != 0){
                //1、-仓储服务→手续费
                res17 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        tcgPurchaseOrder.getVgsbm(),thrOperateCompanyApply.getVgsjc(), "GS0608", "仓储部",
                        TransactionTypeEnum.BusinessType.CCFW_SXF.name, entity.getStorageCommissionCharge().negate(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
                //1、+仓储服务→手续费
                res18 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
                        "GS0608","仓储部",  tcgPurchaseOrder.getVgsbm(),thrOperateCompanyApply.getVgsjc(),
                        TransactionTypeEnum.BusinessType.CCFW_SXF.name, entity.getStorageCommissionCharge(),
                        entity.getCreateTime(), new Date(),remark,entity.getBid(),new Date());
            }

            if(res11.getCode().equals(R.Code.FAILED.value) || res12.getCode().equals(R.Code.FAILED.value) || res13.getCode().equals(R.Code.FAILED.value)
            || res14.getCode().equals(R.Code.FAILED.value) || res15.getCode().equals(R.Code.FAILED.value) || res16.getCode().equals(R.Code.FAILED.value)
            || res17.getCode().equals(R.Code.FAILED.value) || res18.getCode().equals(R.Code.FAILED.value)
            ){//失败
                String reeorMsg = "";
                if(res11.getCode().equals(R.Code.FAILED.value)) reeorMsg = res11.getMsg();
                if(res12.getCode().equals(R.Code.FAILED.value)) reeorMsg = res12.getMsg();
                if(res13.getCode().equals(R.Code.FAILED.value)) reeorMsg = res13.getMsg();
                if(res14.getCode().equals(R.Code.FAILED.value)) reeorMsg = res14.getMsg();
                if(res15.getCode().equals(R.Code.FAILED.value)) reeorMsg = res15.getMsg();
                if(res16.getCode().equals(R.Code.FAILED.value)) reeorMsg = res16.getMsg();
                if(res17.getCode().equals(R.Code.FAILED.value)) reeorMsg = res17.getMsg();
                if(res18.getCode().equals(R.Code.FAILED.value)) reeorMsg = res18.getMsg();
                throw new IllegalArgumentException(reeorMsg);
            }


            if (entity.getIsRefund() == 1) {
                //解冻
                List<TccStockFrozenRunning> tccStockFrozenRunningList = new TccStockFrozenRunning()
                        .setSourceBid(entity.getBid())
                        .setSourceType(TccStockFrozenRunningEnum.SourceType.TCC_ONLINEPURCHASERETURN_PASS.value)
                        .setStatus(1)
                        .where("A.numChange > 0")
                        .queryList();
                for (TccStockFrozenRunning tccStockFrozenRunning : tccStockFrozenRunningList) {
                    tccStockFrozenRunning.setStatus(0);
                    tccStockFrozenRunningMapper.update(tccStockFrozenRunning);
                    String sourceBid = entity.getBid();
                    Long sourceId = entity.getId();
                    Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_ONLINEPURCHASERETURN_FINISH.value;
                    tccStockControlService.thaw(tccStockFrozenRunning.getStockControlId(), tccStockFrozenRunning.getNumChange(), sourceType, sourceBid, sourceId);

                    //出库
                    String remark1 = "线上采购退库单号：" + entity.getBid() + "子件出库";
                    Integer numOut = tccStockFrozenRunning.getNumChange();
                    Integer source = TccStockSourceEnum.Source.TCC_OnlinePurchaseReturn.value;
                    tccStockControlService.outWithRunning(tccStockFrozenRunning.getStockControlId(), remark1, numOut, entity.getBid(),source,entity.getId());
                }
            }

            entity.setEffectStock(1);
            tccOnlinePurchaseReturnMapper.update(entity);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error(e.getMessage());
        }
        return R.ok();
    }
}
